
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import { useUserStore } from "@/store/user";
import { useTabsStore } from "@/store/tabs";
// @ts-ignore
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const Layout = () => import("@/layout/index.vue");

export const constantRoutes: RouteRecordRaw[] = [
    { path: "/login", name: "Login", component: () => import("@/views/Login.vue"), meta: { title: "登录" } },
    {
        path: "/",
        name: "Layout",
        component: Layout,
        redirect: "/dashboard",
        children: [
            { path: "dashboard", name: "Dashboard", component: () => import("@/views/Dashboard.vue"), meta: { title: "仪表盘",affix: true,icon: "Grid" } }
        ]
    },
    { path: "/401", name: "401", component: () => import("@/views/Unauthorized.vue"), meta: { title: "未授权" } }
];

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes
});

router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const user = useUserStore();
    const tabs = useTabsStore();

    if (to.path === "/login") {
        next();
        NProgress.done();
        return;
    }

    // 未登录 -> 登录页
    if (!user.token) {
        next({ path: "/login", query: { redirect: to.fullPath } });
        NProgress.done();
        return;
    }

    // 首次登录后拉取菜单 + 动态路由
    if (!user.dynamicAdded) {
        try {
            await user.fetchProfileAndMenus();
            next({ ...to, replace: true });
            return;
        } catch (e) {
            user.logout();
            next("/login");
            NProgress.done();
            return;
        }
    }

    // 记录标签页
    if (to.name !== "Login") {
        tabs.add(to);
    }

    next();
});

router.afterEach(() => NProgress.done());

export default router;